package report

import (
	"../common"
	"../web"
	"strings"
	"time"
)

type QueryDeliveryObj struct {
	common.BaseHandler
}

func (self *QueryDeliveryObj) Prepare() {}

func (self *QueryDeliveryObj) ParameterCheck() bool {
	c_begin := strings.TrimSpace(self.Ctx.Params["fromdate"])
	c_end := strings.TrimSpace(self.Ctx.Params["todate"])
	if c_begin == "" {
		return false
	}
	s_begin, err := time.Parse("2006-01-02 15:04:05", c_begin)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Query Begin Date is invalid.")
		return false
	}
	if len(c_begin) != 19 {
		self.TmplData["error"] = common.GetText(self.Lang, "Query Begin Date is invalid.")
		return false
	}
	if c_end == "" {
		return false
	}
	s_end, err := time.Parse("2006-01-02 15:04:05", c_end)
	if err != nil {
		self.TmplData["error"] = common.GetText(self.Lang, "Query End Date is invalid.")
		return false
	}
	if len(c_end) != 19 {
		self.TmplData["error"] = common.GetText(self.Lang, "Query End Date is invalid.")
		return false
	}
	if c_begin == c_end {
		self.TmplData["error"] = common.GetText(self.Lang, "The selected time period is not a valid interval.")
		return false
	}
	if s_begin.After(s_end) {
		s_begin, s_end = s_end, s_begin
		c_begin, c_end = c_end, c_begin
	}
	if s_begin.Add(3600 * 24 * 1000 * time.Second).Before(s_end) {
		self.TmplData["error"] = common.GetText(self.Lang, "Date interval can select up to 1000 days.")
		return false
	}

	c_begin = s_begin.Format("2006-01-02 15:04:05")
	c_end = s_end.Format("2006-01-02 15:04:05")

	self.Sqlparas = append(self.Sqlparas, c_begin)
	self.Sqlparas = append(self.Sqlparas, c_end)

	self.TmplData["begindate"] = c_begin
	self.TmplData["enddate"] = c_end

	return true
}

func (self *QueryDeliveryObj) SqlQueryExecute() {
	deliverys := *common.FetchAllRowsPtr(
		`SELECT DISTINCT PONO 
		   FROM SFC_DELIVERY(NOLOCK) 
		  WHERE MODIFYDATE BETWEEN ? AND ? 
		  ORDER BY PONO`,
		self.Usr.Conn, new(common.RecDataStr), self.Sqlparas...)

	self.TmplData["deliverys"] = deliverys
}

func QueryDeliveryHandler(ctx *web.Context) {
	self := new(QueryDeliveryObj)
	self.Ctx = ctx
	self.Html = "querybydelivery.html"
	self.Rightlist = []string{"querydelivery"}
	self.DoQuery(self)
}
